package com.example.demo.filter;

import com.alibaba.fastjson.JSON;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * fileName:MyFilterBodyReaderHttpServletRequestWrapper
 * description: TODO 过滤器处理requestbody获取一次就失效
 * author: LJV
 * createTime:2022/4/9 13:39
 * version:1.0.0
 */
public class MyFilterBodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;
    /**
     * TODO 重写requestbody
     * @param request
     * @throws IOException
     */
    public MyFilterBodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        String sessionStream = getBodyString(request);
        body = sessionStream.getBytes(Charset.forName("UTF-8"));
    }

    /**
     * TODO 拦截解密，校验，重写requestbody
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public MyFilterBodyReaderHttpServletRequestWrapper(HttpServletRequest request, HttpServletResponse response, String clientKey, Boolean ignoreCheckSign) throws Exception {
        super(request);
        String sessionStream = getBodyString(request);
        Map paramMap = (Map) JSON.parse(sessionStream);
        /**
         *自己项目中与合作方的加解密内容
         *如：String data= (String) paramMap.get("data");
         *    String json=xxxxxutil.decrypt(参数);
         */
//        String data= (String) paramMap.get("data");
        body = sessionStream.getBytes(Charset.forName("UTF-8"));
    }

    /**
     * TODO 获取请求Body
     * @param request
     * @return
     * @throws
     */
    public String getBodyString(final ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = cloneInputStream(request.getInputStream());
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    /**
     * TODO 无参获取请求Body
     * @return
     * @throws
     */
    public String getBodyString() {
        if (body == null) {
            return null;
        }
        String str = new String(body);
        return str;
    }

    /**
     * TODO 复制输入流
     * @param inputStream
     * @return
     * @throws
     */
    public InputStream cloneInputStream(ServletInputStream inputStream) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            byteArrayOutputStream.flush();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        InputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        return byteArrayInputStream;
    }
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }

}
